package kau.dao;

import java.util.ArrayList;

import kau.common.DBUtil;
import kau.exception.DuplicationException;
import kau.exception.RecordNotFoundException;
import kau.vo.Tag;

import org.apache.ibatis.session.SqlSession;

public class TagDAOImpl implements TagDAOIF {

	DBUtil db = null;
	private static TagDAOImpl instance;

	private TagDAOImpl() {
		db = DBUtil.getInstance();
	}

	public static TagDAOImpl getInstance() {
		if (instance == null)
			instance = new TagDAOImpl();
		return instance;
	}

	public boolean isExist(String tagId){
		SqlSession session = db.getSession();
		boolean flag = false;
		String result = null;
		
		try{
			
			result = session.selectOne("dbConfig.TagMapper.isExist", tagId);
		}finally{
			if(session != null)
			session.close();
		}
		if(result!= null) flag= true;
		
		return flag;
		
	}
	
	@Override
	public int getCourseId(String tagId) throws RecordNotFoundException {
		// TODO Auto-generated method stub
		int courseId;
		SqlSession session = db.getSession();
		try {
			Integer temp = null;
			temp = session.selectOne("dbConfig.TagMapper.getCourseId", tagId);
			if (temp == null) {
				throw new RecordNotFoundException(tagId + "는 존재 하지 않습니다.");
			} else
				courseId = temp;
		} finally {
			if (session != null)
				session.close();
		}

		return courseId;
	}

	@Override
	public void insert(Tag tag) throws DuplicationException {
		SqlSession session = db.getSession();
		if(isExist(tag.getTagId())) throw new DuplicationException(tag.getTagId());
		try{
			session.insert("dbConfig.TagMapper.insert",tag);
			session.commit();
		}finally{
			if(session != null)
			session.close();
		}
		
		
	}

	@Override
	public void delete(String tagId) throws RecordNotFoundException {
		SqlSession session = db.getSession();
		if(!isExist(tagId)) throw new RecordNotFoundException(tagId);
		try{
			session.delete("dbConfig.TagMapper.delete",tagId);
			session.commit();
		}finally{
			if(session != null)
			session.close();
		}
	}

	@Override
	public ArrayList<Tag> getAllTagLists() {
		ArrayList<Tag> tagList = new ArrayList<Tag>();
		SqlSession session = db.getSession();
		
		try{
			tagList = (ArrayList) session.selectList("dbConfig.TagMapper.getAllTagLists");
		} finally{
		if(session != null)
		session.close();
		}
		return tagList;
	}

}
